<?php

namespace console\db\channels;

use Yii;
use yii\db\Query;

/**
 * 数据表直接复制迁移
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class MergeTableTransferMigration extends TransferTableMigration {

    public $tableName = 'trend_log';

    const PART_SIZE = 50000;
    const MERGE_SIZE = 2000000;

    /**
     * @inheritdoc
     */
    public $sourceDb = 'olddb';
    public static $types = [
        'exp' => 0,
        'orange' => 1,
        'gold' => 2,
        'cash' => 3,
    ];

    /**
     * @inheritdoc
     */
    public function buildQuery() {
        $begintime = strtotime($this->year . '-01-01 00:00:00');
        $endtime = strtotime($this->year . '-12-31 23:59:59');
        return (new Query())->from('{{%' . $this->sourceTable . '}}')->andWhere([
            'between', 'inputtime', $begintime, $endtime
        ]);
    }

    /**
     * @inheritdoc
     */
    public function validateTransfer(&$data) {
        if (!parent::validateTransfer($data)) {
            return false;
        }
        $type = $data['ctype'];
        $data['ctype'] = static::$types[$type];
        if ($data['current'] < 0 && !$data['ctype']) {
            return false;
        }
        return true;
    }

    /**
     * @inheritdoc
     */
    public function getTransferOptions() {
        $sourceTableName = $this->tableName . '_' . $this->year;
        return [
            'table' => [
                $sourceTableName => 'credit_log',
            ],
            'columns' => [
                'user_id' => 'uid',
                'type' => 'ctype',
                'num' => 'amount',
                'current',
                'rule_id' => 'ruleid',
                'mark',
                'created_at' => 'inputtime',
            ]
        ];
    }

}
